import React, { useState , useEffect} from 'react';

type Message = {
  type: 'user' | 'assistant' | 'system';
  content: string;
  action?: 'input' | 'response' | 'error';
};
import { Layout } from 'antd';
import HeaderBar from './common/HeaderBar';
import SiderNav from './common/SiderNav';
import ListMessages from './chat/ListMessages';
import InputQuestion from './chat/InputQuestion';
import { STORAGE_KEYS, getStorageItem } from '../utils/storage';
import SelectConfigure from './chat/SelectConfigure';
import { fetchApi } from '../api';
import { getItemContent, MessageItem} from '../api/chat';

type ApiResponse = {
  messages: MessageItem[];
};
import { initSession } from '../api/session'; // 假设导入路径正确

const { Content, Sider } = Layout;

const ChatPage = () => {
    const [session_id, setSessionId] = useState('');

    useEffect(() => {
        const fetchSessionId = async () => {
            const id = await initSession();
            setSessionId(id);
        };
        fetchSessionId();
    }, []);

  const [messages, setMessages] = useState<MessageItem[]>([]);
  const [input, setInput] = useState('');
  // 重新初始化配置状态（从存储读取初始值）
  const [provider, setProvider] = useState(() => getStorageItem(STORAGE_KEYS.SELECTED_PROVIDER) || '');
  const [model, setModel] = useState(() => getStorageItem(STORAGE_KEYS.SELECTED_MODEL) || '');
  const [mcp_server, setMcpServer] = useState(() => getStorageItem(STORAGE_KEYS.SELECTED_MCP) || '');

  const handleSend = async () => {
    if (!input.trim()) return;
    // 创建新消息
    const newMessage: MessageItem = {
      id: 0,
      role: 'user', 
      content: input,
      thinking: null,
      provider: provider,
      model: model,
      created_at: new Date().toISOString(),
      tool: null
    };
     // 使用父组件管理的配置状态调用 API
    const response = await fetchApi('/api/chat', 'POST', {
      session_id,
      question: input,
      provider,
      mcp_server,
      selected_model: model
    });
    
    // 处理API响应消息
    const responseMessages = response.messages.slice(2).map((msg: any) => ({
      id: msg.id,
      role: msg.role || 'assistant',
      content: msg.content,
      thinking: msg.thinking || null,
      provider: msg.provider || null,
      model: msg.model || null,
      created_at: msg.created_at || null,
      tool: msg.tool || null
    }));
    setMessages([newMessage, ...responseMessages])
    console.log("united message:", newMessage, messages)
  };

  return (
    <Layout style={{ minHeight: '100vh', width: '100%' }}>
      <HeaderBar />
      <Layout>
        <Sider 
          width="15%"
          style={{ height: '100%', backgroundColor: '#f8f9fa' }}
        >
          <SiderNav 
            defaultSelectedKeys={['1']}
            defaultOpenKeys={['settings']}
          />
        </Sider>
        <Content style={{ padding: '16px', width: 'auto' }}>
          {/* 传递状态更新回调给 ModelConfigure */}
          <SelectConfigure  
            onProviderChange={setProvider}
            onModelChange={setModel}
            onMcpServerChange={setMcpServer}
          />
          <ListMessages messages={messages} />
          <InputQuestion 
            input={input} 
            setInput={setInput} 
            handleSend={handleSend} 
          />
        </Content>
      </Layout>
    </Layout>
  );
};

export default ChatPage;